package com.kun.video.ui.pane;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ArrayUtil;
import com.kun.video.context.ContextService;
import com.kun.video.thread.ComThreadPool;
import com.kun.video.ui.KunComponent;
import com.kun.video.ui.control.button.KunButton;
import com.kun.video.util.ImageUtil;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.HBox;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.concurrent.CompletableFuture;

/**
 * 视频工具栏容器
 *
 * @author gzc
 * @since 2025/5/22
 **/
public class VideoToolBox extends HBox implements KunComponent {
    private static final Logger log = LoggerFactory.getLogger(VideoToolBox.class);
    private static final String CSS_CLASS = "video-tool-box";

    private ComThreadPool comThreadPool;

    /**
     * 截图功能按钮
     */
    private KunButton snapshotButton = new KunButton("截图", "视频当前帧截图保存到本地磁盘");

    private WritableImage videoImage;

    public VideoToolBox() {
        initialize();
    }

    @Override
    public Parent getNode() {
        return this;
    }

    @Override
    public String getStyleName() {
        return CSS_CLASS;
    }

    @Override
    public void initStyleClass() {
        KunComponent.super.initStyleClass();
    }

    @Override
    public void initLayout() {
        setAlignment(Pos.CENTER_LEFT);
        setPadding(new Insets(10));
        setSpacing(5);
        getChildren().addAll(snapshotButton);
    }

    @Override
    public void initStyle() {
    }

    @Override
    public void initDimensions() {
    }

    @Override
    public void reactiveDimensions(double width, double height) {
    }

    public CompletableFuture<Void> snapshot(WritableImage writableImage, File outputDir) {
        CompletableFuture<Void> future = new CompletableFuture<>();
        if (writableImage == null || outputDir == null) {
            log.warn("截图失败");
            return future;
        }
        String outputFileName = UUID.fastUUID().toString(true) + ".png";
        String outputFilePath = outputDir.getAbsolutePath() + File.separator + outputFileName;
        // 保存截图到本地磁盘
        return CompletableFuture.runAsync(() -> ImageUtil.savePng(writableImage, outputFilePath));
    }

    @Override
    public void initListeners() {
        snapshotButton.action(() -> snapshot(videoImage, new File("f:\\")));
    }

    @Override
    public void dispose() {
    }

    @Override
    public void initData() {
        comThreadPool = ContextService.getBean(ComThreadPool.class);
    }

    public void dataPassing(Object... params) {
        if (ArrayUtil.isEmpty(params)) {
            return;
        }
        for (Object param : params) {
            if (param instanceof WritableImage writableImage) {
                this.videoImage = writableImage;
            }
        }
    }
}